﻿exports.save_sms = function (req, res) {
    
    var fs = require("fs");
    var pconfig = require("../common/config").config;
    var DateUtils = require("../common/dateUtils").DateUtils;
    var Commons = require("../common/Commons").Commons;
    var now = new Date();
    var d = DateUtils.dateToString(now);
    var suffix = DateUtils.dateToString(now, "yyyy-MM-dd");
    var fullPath = pconfig.filePathPrefix + pconfig.smsFileName + "." + suffix;
    if (req.method == "POST") {
        var DBUtils = null;
        var dbType = pconfig.useDB;
        var url = null;
        if (dbType == "mongo") {
            url = pconfig.dbUrl;
            DBUtils = require("../common/MongoDBUtils").DBUtils;
        } else if (dbType == "mysql") {
            url = pconfig.mysqlConfig;
            DBUtils = require("../common/MysqlDBUtils").DBUtils;
        }
        
        var EncryptUtils = require("../common/EncryptUtils").EncryptUtils;
        var connPromise = DBUtils.getConnection(url, null);
        connPromise.then(function (rdb) {
            var db = rdb.result;
            var datas = req.body;
            var isSuccess = true;
            var promiseQueryAll = [];
            for (var i = 0; i < datas.length; i++) {
                var data = datas[i];
                
                //console.log('[' + d + ']' + JSON.stringify(datas[i]) + '\n');                
                
                var content = data.deviceId + "_" + data.aid;
                data._id = EncryptUtils.md5(content);
                
                promiseQueryAll.push(DBUtils.find(db, "sms", { _id: data._id }, { index: i, data: data }));
                
                
                fs.appendFile(fullPath, '[' + d + ']' + JSON.stringify(datas[i]) + '\n', function (err) {
                    if (err) {
                        console.log(err);
                    }
                });
            }
            Promise.all(promiseQueryAll).then(function (dataList) {
                var promiseInsertAll = [];
                for (var j = 0; j < dataList.length; j++) {
                    var r = dataList[j];                    
                    if (r.result && r.result.length > 0) {                    
                    } else {
                        promiseInsertAll.push(DBUtils.insert(db, "sms", r.object.data));
                    }
                }
                Promise.all(promiseInsertAll).then(function (tempList) {
                    for (var j = 0; j < tempList.length; j++) {
                        var r = tempList[j];
                        console.log("insert " + JSON.stringify(r.object.data) + " successful.");
                    }
                    Commons.finishDBAndSetResult(db, dbType, res, isSuccess);
                }).catch(function (err) {
                    console.log("insert " + JSON.stringify(data) + " error.\n" + err);                    
                    Commons.finishDBAndSetResult(db, dbType, res, false);
                });
            }).catch(function (err) {
                console.log(err);
                isSuccess = false;
                    
            });
        }).catch(function (err) {
            console.log(err);
            var result = { code: RESULT_ERROR, interval: 10000, message: "save data error." };
            res.send(JSON.stringify(result));
        });
    } 
};